package com.example.buyticketlishi.view.ac;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.baselibrary.Base.BaseActivity;
import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.ThreadManager;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.buyticketlishi.R;
import com.example.buyticketlishi.RequestHelp.httpUtils;
import com.example.buyticketlishi.adapter.ImforIdListAdapter;
import com.example.buyticketlishi.bean.LiShihandSetReserveProductRequsetBean;
import com.example.buyticketlishi.bean.LiShihandSetReserveProductResultBean;
import com.example.buyticketlishi.bean.LiShihandSetReserveProductResultSecondBean;
import com.example.buyticketlishi.utils.PeterTimeCountRefresh;
import com.example.buyticketlishi.wightview.TipCenterShow;
import com.google.gson.Gson;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderExceptionListener;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class InformationOldActivity extends BaseActivity {

    private Button btBuyNow;
    private TextView tvNumber;
    private TextView tvMoney;
    private LiShihandSetReserveProductRequsetBean allData;
    private String allNumber;
    private String allMoney;
    private Button back;
    private TextView tvIdInputTip;
    private RecyclerView rvIdList;

    //语音的引入
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    // 曲阜 中身份证识别 新的集成

    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = null;

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.example.scarx.idcardreader.USB_PERMISSION";
    private Thread thread;
    private int InputIdNumber = 0;

    private long timeNew;
    private long timeOld;
    private String OldID;

    private PeterTimeCountRefresh timer;
    private String showMessage;

    //身份证录入 数据
    private List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean> certificateParamListBeanList;

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        try {
                            OpenDevice();
                        } catch (Exception e) {

                        }
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };
    private ImforIdListAdapter imforIdListAdapter;
    private EditText etPhone;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getView() {
        return R.layout.activity_information;
    }

    @Override
    public void init() {

        //获取TTS引擎
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }


        if (certificateParamListBeanList == null) {
            certificateParamListBeanList = new ArrayList<>();
        }

        mContext = this;
        Intent intent = getIntent();
        Bundle myData = intent.getBundleExtra("myData");

        allData = (LiShihandSetReserveProductRequsetBean) myData.getParcelable("allData");
        allNumber = myData.getString("allNumber");
        allMoney = myData.getString("allMoney");

        //获取上个页面传递过来的数据
        tvNumber = findViewById(R.id.tv_information_number);
        tvMoney = findViewById(R.id.tv_information_money);
        back = findViewById(R.id.bt_back_home);
        tvIdInputTip = findViewById(R.id.tv_phone_number_title_tip);
        etPhone = findViewById(R.id.et_information_input);

        btBuyNow = findViewById(R.id.bt_information_to_pay);

        rvIdList = findViewById(R.id.rv_information_id_show);


        imforIdListAdapter = new ImforIdListAdapter(certificateParamListBeanList, InformationOldActivity.this, allData);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvIdList.setLayoutManager(linearLayoutManager);
        rvIdList.setAdapter(imforIdListAdapter);

        tvNumber.setText("购票张数： " + allNumber);
        tvMoney.setText("合计金额： " + allMoney);

        //拿到数据，然后对tip  进行显示     注意
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("先录入");

        InputIdNumber = 0;
        for (int i = 0; i < allData.getProductParamList().size(); i++) {
            //标识为1 说明是要身份证输入的
            if (allData.getProductParamList().get(i).getCertificateFlag() == 1) {
                if (stringBuffer.length() > 4) {
                    stringBuffer.append(" 再录入");
                }
                stringBuffer.append(allData.getProductParamList().get(i).getScenicTicketName()+ "证件 * " + allData.getProductParamList().get(i).getSaleSum() + ",");
                InputIdNumber = InputIdNumber + allData.getProductParamList().get(i).getSaleSum();
            }
        }

        if ((stringBuffer.toString()).equals("先录入")) {
            tvIdInputTip.setVisibility(View.GONE);
            showMessage = "无需录了证件信息";
        } else {
            tvIdInputTip.setVisibility(View.VISIBLE);
            showMessage = stringBuffer.toString();

        }




        //身份证 开启读取
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);
        //开启身份证读卡器
        if (bopen) {
            return;
        }


        RequestDevicePermission();

        doThing();

        timer = new PeterTimeCountRefresh(1000 * 300, 1000, (TextView) findViewById(R.id.tv_over_time));
        timer.start();
        timer.setTimeOverListener(new PeterTimeCountRefresh.TimeOverListener() {
            @Override
            public void timeOver() {
                //倒计时结束，结束页面
                startActivity(new Intent(InformationOldActivity.this, MainActivity.class));
            }
        });
    }


    private void doThing() {

        btBuyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //校验需要身份证的地方，是否一致
                for (int i = 0; i < allData.getProductParamList().size(); i++) {
                    if (allData.getProductParamList().get(i).getCertificateFlag() == 1) {
                        if (allData.getProductParamList().get(i).getCertificateParamList() != null) {
                            if (!(allData.getProductParamList().get(i).getSaleSum() == allData.getProductParamList().get(i).getCertificateParamList().size())) {
                                // 如果长度不相等，说明数据不一致，那么就不进行下一步。并且提示
                                SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "实名制人数不一致，请确认");
                                PlayAudioFile(allData.getProductParamList().get(i).getScenicTicketName() + "实名制人数不一致，请确认");
                                return;
                            }
                        } else {
                            if (allData.getProductParamList().get(i).getSaleSum() > 0) {
                                SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "需要实名制信息录入");
                                PlayAudioFile(allData.getProductParamList().get(i).getScenicTicketName() + "需要实名制信息录入");
                                return;
                            }
                        }

                    }

                }

                // 判断电话号码是否输入
                if (StringUtil.isNullOrEmpty(etPhone.getText().toString())) {
                    SelfToastUtil.getInstance().show("请输入联系人手机号码");
                    PlayAudioFile("请输入联系人手机号码");
                    return;
                }

                if (!StringUtil.isChinaPhoneLegal(etPhone.getText().toString())) {
                    SelfToastUtil.getInstance().show("请输入正确的手机号码");
                    PlayAudioFile("请输入正确的手机号码");
                    return;
                }


                //如果都正确，那么就去生成订单
                CreatOrder();


            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void CreatOrder() {
        //由于有两种返回，所以要换一种请求方式，不知道那个傻子定义的这种方式，脑残
//        RetrofitClient.getInstance(InformationActivity.this, Base_URL, headers).LiShihandSetReserveProduct(allData, new BaseSubscriber<LiShihandSetReserveProductResultBean>(InformationActivity.this) {
//            @Override
//            public void onError(ExceptionHandle.ResponeThrowable e) {
//                SelfToastUtil.getInstance().show(e.message);
//
//            }
//
//            @Override
//            public void onNext(LiShihandSetReserveProductResultBean liShihandSetReserveProductResultBean) {
//                String code = liShihandSetReserveProductResultBean.getCode();
//                if (code.equals("200")) {
//                    //如果生成订单成功，那么就去获取支付信息，并且调转支付页面
//
//                    Intent intent = new Intent(InformationActivity.this, PaySelectActivity.class);
//                    intent.putExtra("orderBatchNo", liShihandSetReserveProductResultBean.getData().getOrderBatchNo());
//                    intent.putExtra("allMoney", allMoney);
//                    startActivity(intent);
//
//                }
//                else if (code.equals("52007")){
//
//
//                }else {
//                    SelfToastUtil.getInstance().show(liShihandSetReserveProductResultBean.getMessage());
//                }
//            }
//        });

        // 第二种请求方式，方便返回两种结果
        final JSONObject param = new JSONObject();

        try {
            param.put("saleChannelType", allData.getSaleChannelType());
            param.put("printTicketMode", allData.getPrintTicketMode());
            param.put("remark", allData.getRemark());

            if (allData.getProductParamList() != null) {
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < allData.getProductParamList().size(); i++) {
                    JSONObject paramIn = new JSONObject();

                    paramIn.put("arriveDT", allData.getProductParamList().get(i).getArriveDT());
                    paramIn.put("scenicTicketId", allData.getProductParamList().get(i).getScenicTicketId());
                    paramIn.put("shiftsId", allData.getProductParamList().get(i).getShiftsId());
                    paramIn.put("saleSum", allData.getProductParamList().get(i).getSaleSum());
                    paramIn.put("customerDiscountType", allData.getProductParamList().get(i).getCustomerDiscountType());

                    if (allData.getProductParamList().get(i).getTimeControlParamList() != null) {
                        JSONArray jsonArrayTime = new JSONArray();
                        for (int i1 = 0; i1 < allData.getProductParamList().get(i).getTimeControlParamList().size(); i1++) {
                            JSONObject paramTime = new JSONObject();

                            paramTime.put("projectId", allData.getProductParamList().get(i).getTimeControlParamList().get(i1).getProjectId());
                            paramTime.put("ordTimeControlId", allData.getProductParamList().get(i).getTimeControlParamList().get(i1).getOrdTimeControlId());

                            jsonArrayTime.put(i1, paramTime);
                        }
                        paramIn.put("timeControlParamList", jsonArrayTime);
                    }


                    if (allData.getProductParamList().get(i).getCertificateParamList() != null) {
                        JSONArray jsonArrayCertificate = new JSONArray();
                        for (int i2 = 0; i2 < allData.getProductParamList().get(i).getCertificateParamList().size(); i2++) {
                            JSONObject paramCertificate = new JSONObject();

                            paramCertificate.put("certificateName", allData.getProductParamList().get(i).getCertificateParamList().get(i2).getCertificateName());
                            paramCertificate.put("certificateTypeId", allData.getProductParamList().get(i).getCertificateParamList().get(i2).getCertificateTypeId());
                            paramCertificate.put("certificateNo", allData.getProductParamList().get(i).getCertificateParamList().get(i2).getCertificateNo());

                            jsonArrayCertificate.put(i2, paramCertificate);
                        }
                        paramIn.put("certificateParamList", jsonArrayCertificate);
                    }

                    jsonArray.put(i, paramIn);
                }
                param.put("productParamList", jsonArray);
            }

        } catch (JSONException e) {
            e.printStackTrace();

        }



        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                String url = Base_URL + "/windowSaleTicketAction/handSetReserveProduct";
                String ss = httpUtils.postJsonLishi(url, param);

                try {
                    LiShihandSetReserveProductResultBean resultBean = new Gson().fromJson(ss, LiShihandSetReserveProductResultBean.class);
                    int code = Integer.parseInt(resultBean.getCode());
                    if (code == 200) {
                        Intent intent = new Intent(InformationOldActivity.this, PaySelectActivity.class);
                        intent.putExtra("orderBatchNo", resultBean.getData().getOrderBatchNo());
                        intent.putExtra("allMoney", allMoney);
                        startActivity(intent);
                    }else {
                        SelfToastUtil.getInstance().show(resultBean.getMessage());
                    }
                } catch (Exception e) {
                    LiShihandSetReserveProductResultSecondBean resultBean = new Gson().fromJson(ss, LiShihandSetReserveProductResultSecondBean.class);
                    int code = Integer.parseInt(resultBean.getCode());
                    if (code == 52007) {
                        //选择了方式，跳转下一个界面
                        Intent intent = new Intent(InformationOldActivity.this, PayMoneyActivity.class);
                        intent.putExtra("orderBatchNo", resultBean.getData().get(0).getOrderBatchNo());
//                        intent.putExtra("paymentTypeId", paymentTypeId);
                        intent.putExtra("allMoney", allMoney);
                        startActivity(intent);
                        SelfToastUtil.getInstance().show(resultBean.getMessage());
                    }else {
                        SelfToastUtil.getInstance().show(resultBean.getMessage());
                    }
                }
            }
        });


    }

    public void OpenDevice() {
        if (bopen) {
            SelfToastUtil.getInstance().show("设备已连接");
            return;
        }
        try {
            startIDCardReader();
            IDCardReaderExceptionListener listener = new IDCardReaderExceptionListener() {
                @Override
                public void OnException() {
                    //出现异常，关闭设备
                    CloseDevice();
                    //当前线程为工作线程，若需操作界面，请在UI线程处理
                    runOnUiThread(new Runnable() {
                        public void run() {
                            SelfToastUtil.getInstance().show("设备发生异常，断开连接！");
                        }
                    });
                }
            };
            idCardReader.open(0);
            idCardReader.setIdCardReaderExceptionListener(listener);
            bStoped = false;
            mReadCount = 0;
            writeLogToFile("连接设备成功");
//            SelfToastUtil.getInstance().show("连接成功");
            bopen = true;
            countdownLatch = new CountDownLatch(1);
            thread = new Thread(new Runnable() {
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            if (idCardReader != null) {
                                idCardReader.findCard(0);
                                idCardReader.selectCard(0);
                            }
                        } catch (IDCardReaderException e) {
                            //continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int retType = 0;
                        try {
                            retType = idCardReader.readCardEx(0, 0);
                        } catch (Exception e) {
                            writeLogToFile("读卡失败，错误信息：" + e.getMessage());
                        }
                        if (retType == 1 || retType == 2 || retType == 3) {
                            final long nTickUsed = (System.currentTimeMillis() - nTickstart);
                            final int final_retType = retType;
                            writeLogToFile("读卡成功：" + (++mReadCount) + "次" + "，耗时：" + nTickUsed + "毫秒");
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (final_retType == 1) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名adb
                                        final String strName = idCardInfo.getName();
                                        //民族
                                        String strNation = idCardInfo.getNation();
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        final String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();

                                        final String Sex = idCardInfo.getSex();

                                        timeNew = TimeUtil.getLocationTimeLong();

                                        //计算年龄
                                        int age = Integer.parseInt((TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DATE_EN)).substring(0, 4)) - Integer.parseInt(strBorn.substring(0, 4));

                                        if (checkIDAgain(strID)) {
                                            return;
                                        }

                                        for (int i = 0; i < allData.getProductParamList().size(); i++) {

                                            //要判断身份证输入是否已经满了，如果满了，那么就提示用户，证件号已满，不需要再添加了  InputIdNumber
                                            if (certificateParamListBeanList.size() >= InputIdNumber) {
                                                SelfToastUtil.getInstance().show("身份证实名录入票已完成，无需录入更多身份证证件");
                                            }

                                            int certificateFlag = allData.getProductParamList().get(i).getCertificateFlag();
                                            //如果是需要录入身份证的  1 就是实名制 ，如果是实名制，那么去查询要几个实名制
                                            if (certificateFlag == 1) {
                                                int saleSum = allData.getProductParamList().get(i).getSaleSum();
                                                for (int i1 = 0; i1 < saleSum; i1++) {
                                                    //如果添加满了，那就切换下一个
                                                    if (allData.getProductParamList().get(i).getCertificateParamList() != null && allData.getProductParamList().get(i).getCertificateParamList().size() >= saleSum) {
                                                        break;
                                                    }
                                                    //还要判断这个里面是否已经添加过  就退出，如果不知道 就 下一步
                                                    if (allData.getProductParamList().get(i).getCertificateParamList() != null && allData.getProductParamList().get(i).getCertificateParamList().size() > 0) {
                                                        for (int i2 = 0; i2 < allData.getProductParamList().get(i).getCertificateParamList().size(); i2++) {
                                                            if (allData.getProductParamList().get(i).getCertificateParamList().get(i2) != null && allData.getProductParamList().get(i).getCertificateParamList().get(i2).getCertificateName().equals(strName)) {
//                                                                SelfToastUtil.getInstance().show("该证件已经添加，请勿重复添加");
//                                                                break;
                                                            } else {
                                                                //去添加的时候，先判断年龄  如果 最小年龄，和最大年龄是 正常的话，那么不是 老年卡类型
                                                                if (allData.getProductParamList().get(i).getMinAge() < allData.getProductParamList().get(i).getMaxAge()) {
                                                                    if (allData.getProductParamList().get(i).getMinAge() <= age && age <= allData.getProductParamList().get(i).getMaxAge()) {
                                                                        //如果年龄在这之间那就可以去添加
                                                                        LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean certificateParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean();

                                                                        certificateParamListBean.setCertificateName(strName);
                                                                        certificateParamListBean.setCertificateNo(strID);
                                                                        certificateParamListBean.setCertificateTypeId(1);
                                                                        certificateParamListBean.setTicketName(allData.getProductParamList().get(i).getScenicTicketName());

//                                                    allData.getProductParamList().get(i).getCertificateParamList().get(i1).setCertificateTypeId(1);
                                                                        List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean> certificateParamList = allData.getProductParamList().get(i).getCertificateParamList();
                                                                        if (certificateParamList == null) {
                                                                            certificateParamList = new ArrayList<>();
                                                                        }

                                                                        if (certificateParamListBeanList.size() >= InputIdNumber) {
                                                                            SelfToastUtil.getInstance().show("身份证实名录入票已完成，无需录入更多身份证证件");
                                                                            return;
                                                                        }

                                                                        certificateParamList.add(certificateParamListBean);

                                                                        allData.getProductParamList().get(i).setCertificateParamList(certificateParamList);

                                                                        certificateParamListBeanList.add(certificateParamListBean);

                                                                        if (certificateParamListBeanList.size() >= InputIdNumber) {
//                                                                            SelfToastUtil.getInstance().show("身份证信息录入完毕，请填写联系人手机号");
                                                                            TipCenterShow tipCenterShow = new TipCenterShow(InformationOldActivity.this);
                                                                            tipCenterShow.show();
                                                                        }

                                                                        imforIdListAdapter.notifyDataSetChanged();
                                                                        break;
                                                                    } else {
                                                                        SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "由于年龄限制，无法添加当前卡");
                                                                        break;
                                                                    }

                                                                } else {
                                                                    // 如果最小年龄大于最大年龄，那么就是最大年龄是0 ，是老年卡类型，只要比较身份证年龄是否大于最小值就可以，大于就过
                                                                    if (allData.getProductParamList().get(i).getMinAge() < age) {
                                                                        //如果年龄在这之间那就可以去添加
                                                                        LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean certificateParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean();

                                                                        certificateParamListBean.setCertificateName(strName);
                                                                        certificateParamListBean.setCertificateNo(strID);
                                                                        certificateParamListBean.setCertificateTypeId(1);
                                                                        certificateParamListBean.setTicketName(allData.getProductParamList().get(i).getScenicTicketName());

//                                                    allData.getProductParamList().get(i).getCertificateParamList().get(i1).setCertificateTypeId(1);
                                                                        List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean> certificateParamList = allData.getProductParamList().get(i).getCertificateParamList();
                                                                        if (certificateParamList == null) {
                                                                            certificateParamList = new ArrayList<>();
                                                                        }

                                                                        if (certificateParamListBeanList.size() >= InputIdNumber) {
                                                                            SelfToastUtil.getInstance().show("身份证实名录入票已完成，无需录入更多身份证证件");
                                                                            return;
                                                                        }

                                                                        certificateParamList.add(certificateParamListBean);

                                                                        allData.getProductParamList().get(i).setCertificateParamList(certificateParamList);

                                                                        certificateParamListBeanList.add(certificateParamListBean);

                                                                        if (certificateParamListBeanList.size() >= InputIdNumber) {
//                                                                            SelfToastUtil.getInstance().show("身份证信息录入完毕，请填写联系人手机号");
                                                                            TipCenterShow tipCenterShow = new TipCenterShow(InformationOldActivity.this);
                                                                            tipCenterShow.show();
                                                                        }
                                                                        imforIdListAdapter.notifyDataSetChanged();
                                                                        break;
                                                                    } else {
                                                                        SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "由于年龄限制，无法添加当前卡");
                                                                        break;
                                                                    }
                                                                }

                                                            }
                                                        }

                                                    } else {

                                                        //去添加的时候，先判断年龄  如果 最小年龄，和最大年龄是 正常的话，那么不是 老年卡类型
                                                        if (allData.getProductParamList().get(i).getMinAge() < allData.getProductParamList().get(i).getMaxAge()) {
                                                            if (allData.getProductParamList().get(i).getMinAge() <= age && age <= allData.getProductParamList().get(i).getMaxAge()) {
                                                                //如果年龄在这之间那就可以去添加
                                                                LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean certificateParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean();

                                                                certificateParamListBean.setCertificateName(strName);
                                                                certificateParamListBean.setCertificateNo(strID);
                                                                certificateParamListBean.setCertificateTypeId(1);
                                                                certificateParamListBean.setTicketName(allData.getProductParamList().get(i).getScenicTicketName());

//                                                    allData.getProductParamList().get(i).getCertificateParamList().get(i1).setCertificateTypeId(1);
                                                                List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean> certificateParamList = allData.getProductParamList().get(i).getCertificateParamList();
                                                                if (certificateParamList == null) {
                                                                    certificateParamList = new ArrayList<>();
                                                                }

                                                                if (certificateParamListBeanList.size() >= InputIdNumber) {
                                                                    SelfToastUtil.getInstance().show("身份证实名录入票已完成，无需录入更多身份证证件");
                                                                    return;
                                                                }

                                                                certificateParamList.add(certificateParamListBean);

                                                                allData.getProductParamList().get(i).setCertificateParamList(certificateParamList);

                                                                certificateParamListBeanList.add(certificateParamListBean);


                                                                if (certificateParamListBeanList.size() >= InputIdNumber) {
//                                                                    SelfToastUtil.getInstance().show("身份证信息录入完毕，请填写联系人手机号");
                                                                    TipCenterShow tipCenterShow = new TipCenterShow(InformationOldActivity.this);
                                                                    tipCenterShow.show();
                                                                }

                                                                imforIdListAdapter.notifyDataSetChanged();

                                                            } else {
                                                                SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "由于年龄限制，无法添加当前卡");

                                                            }

                                                        } else {
                                                            // 如果为空，那么就要更具年龄去添加
                                                            // 如果最小年龄大于最大年龄，那么就是最大年龄是0 ，是老年卡类型，只要比较身份证年龄是否大于最小值就可以，大于就过
                                                            if (allData.getProductParamList().get(i).getMinAge() < age) {
                                                                //如果年龄在这之间那就可以去添加
                                                                LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean certificateParamListBean = new LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean();

                                                                certificateParamListBean.setCertificateName(strName);
                                                                certificateParamListBean.setCertificateNo(strID);
                                                                certificateParamListBean.setCertificateTypeId(1);
                                                                certificateParamListBean.setTicketName(allData.getProductParamList().get(i).getScenicTicketName());

//                                                    allData.getProductParamList().get(i).getCertificateParamList().get(i1).setCertificateTypeId(1);
                                                                List<LiShihandSetReserveProductRequsetBean.ProductParamListBean.CertificateParamListBean> certificateParamList = allData.getProductParamList().get(i).getCertificateParamList();
                                                                if (certificateParamList == null) {
                                                                    certificateParamList = new ArrayList<>();
                                                                }

                                                                if (certificateParamListBeanList.size() >= InputIdNumber) {
                                                                    SelfToastUtil.getInstance().show("身份证实名录入票已完成，无需录入更多身份证证件");
                                                                    return;
                                                                }

                                                                certificateParamList.add(certificateParamListBean);

                                                                allData.getProductParamList().get(i).setCertificateParamList(certificateParamList);

                                                                certificateParamListBeanList.add(certificateParamListBean);

                                                                if (certificateParamListBeanList.size() >= InputIdNumber) {
//                                                                    SelfToastUtil.getInstance().show("身份证信息录入完毕，请填写联系人手机号");
                                                                    TipCenterShow tipCenterShow = new TipCenterShow(InformationOldActivity.this);
                                                                    tipCenterShow.show();
                                                                }

                                                                imforIdListAdapter.notifyDataSetChanged();

                                                            } else {
                                                                SelfToastUtil.getInstance().show(allData.getProductParamList().get(i).getScenicTicketName() + "由于年龄限制，无法添加当前卡");

                                                            }
                                                        }

                                                    }


                                                }
                                            }
                                        }

                                    } else if (final_retType == 2) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                        //中文名
                                        String strCnName = idprpCardInfo.getCnName();
                                        //英文名
                                        String strEnName = idprpCardInfo.getEnName();
                                        //国家/国家地区代码
                                        String strCountry = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                        //出生日期
                                        String strBorn = idprpCardInfo.getBirth();
                                        //身份证号
                                        String strID = idprpCardInfo.getId();
                                        //有效期限
                                        String strEffext = idprpCardInfo.getValidityTime();


                                    } else {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名
                                        String strName = idCardInfo.getName();
                                        //民族,港澳台不支持该项
                                        String strNation = "";
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();
                                        //签发机关
                                        String strIssueAt = idCardInfo.getDepart();
                                        //通行证号
                                        String strPassNum = idCardInfo.getPassNum();
                                        //签证次数
                                        int visaTimes = idCardInfo.getVisaTimes();


                                    }
                                }
                            });
                        }
                    }
                    countdownLatch.countDown();
                }
            });
            thread.start();
        } catch (IDCardReaderException e) {
            SelfToastUtil.getInstance().show("连接设备失败");
        }
    }


    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i("zyf", "onInit: TTS引擎初始化成功");

                if ((showMessage).contains("先录入")) {
                   PlayAudioFile("请输入身份证信息");
                } else {
                    PlayAudioFile("请填写手机号码");
                }
            } else {
                Log.i("zyf", "onInit: TTS引擎初始化失败");
            }
        }
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i("zyf", "中文设置失败");
        } else {
            Log.i("zyf", "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }


    // 返回 true  相同 小于  10 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 5) {
//            SelfToastUtil.getInstance().show("同一张身份证，1秒内不可重复操作");
            System.out.println("zyf  未超过5秒 拒绝访问" + TimeUtil.getLocationTime());
            return true;
        } else {
            System.out.println("zyf  超过5秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }

    private void startIDCardReader() {
        if (null != idCardReader) {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
    }

    public static void writeLogToFile(String log) {
        try {
            File dirFile = new File("/sdcard/zkteco/");  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = "/sdcard/zkteco/idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void CloseDevice() {
        if (!bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        if (null != countdownLatch) {
            try {
                countdownLatch.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        bopen = false;
    }

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }

        if (thread != null) {
            bStoped = true;
            thread.interrupt();
        }

        IDCardReaderFactory.destroy(idCardReader);
        mContext.unregisterReceiver(mUsbReceiver);
    }

}
